<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { queryOverviewApi } from '@/api/home'
import { Refresh, Reading, Calendar, Promotion, Opportunity, User, Document } from '@element-plus/icons-vue'

const router = useRouter()

// 页面加载完毕后, 执行查询
onMounted(() => {
  loadOverviewData()
})

// 加载状态
const loading = ref(false)
const error = ref('')
const lastUpdateTime = ref('')

// 概览数据
const overviewData = ref({
  clueTotal: 0,
  clueWaitAllot: 0,
  clueWaitFollow: 0,
  clueFollowing: 0,
  clueFalse: 0,
  clueConvertBusiness: 0,
  businessTotal: 0,
  businessWaitAllot: 0,
  businessWaitFollow: 0,
  businessFollowing: 0,
  businessFalse: 0,
  businessConvertCustomer: 0
})

// 计算属性 - 计算各项数据的百分比
const clueDataPercentage = computed(() => {
  const total = overviewData.value.clueTotal || 1 // 避免除以0
  return {
    clueWaitAllot: Math.round((overviewData.value.clueWaitAllot / total) * 100),
    clueWaitFollow: Math.round((overviewData.value.clueWaitFollow / total) * 100),
    clueFollowing: Math.round((overviewData.value.clueFollowing / total) * 100),
    clueFalse: Math.round((overviewData.value.clueFalse / total) * 100),
    clueConvertBusiness: Math.round((overviewData.value.clueConvertBusiness / total) * 100)
  }
})

const businessDataPercentage = computed(() => {
  const total = overviewData.value.businessTotal || 1 // 避免除以0
  return {
    businessWaitAllot: Math.round((overviewData.value.businessWaitAllot / total) * 100),
    businessWaitFollow: Math.round((overviewData.value.businessWaitFollow / total) * 100),
    businessFollowing: Math.round((overviewData.value.businessFollowing / total) * 100),
    businessFalse: Math.round((overviewData.value.businessFalse / total) * 100),
    businessConvertCustomer: Math.round((overviewData.value.businessConvertCustomer / total) * 100)
  }
})

// 加载概览数据
const loadOverviewData = async () => {
  loading.value = true
  error.value = ''
  try {
    const result = await queryOverviewApi()
    if(result.code) {
      overviewData.value = result.data
      // 更新最后更新时间
      lastUpdateTime.value = formatDateTime(new Date())
      ElMessage.success('数据加载成功')
    } else {
      error.value = result.msg || '获取数据失败'
      ElMessage.error(error.value)
      // 使用模拟数据以便展示
      setMockData()
    }
  } catch (err) {
    console.error('加载概览数据失败:', err)
    error.value = '网络错误，请稍后重试'
    ElMessage.error(error.value)
    // 使用模拟数据以便展示
    setMockData()
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadOverviewData()
}

// 设置模拟数据（当接口不可用时展示）
const setMockData = () => {
  overviewData.value = {
    clueTotal: 9,
    clueWaitAllot: 3,
    clueWaitFollow: 3,
    clueFollowing: 1,
    clueFalse: 0,
    clueConvertBusiness: 2,
    businessTotal: 2,
    businessWaitAllot: 2,
    businessWaitFollow: 0,
    businessFollowing: 0,
    businessFalse: 0,
    businessConvertCustomer: 0
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  const now = new Date(date)
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 快捷操作 - 跳转到对应页面
const goToPage = (path) => {
  router.push(path)
}

// 获取数据项的状态类名
const getDataItemClass = (type) => {
  const statusClasses = {
    clueWaitAllot: 'status-wait-allot',
    clueWaitFollow: 'status-wait-follow',
    clueFollowing: 'status-following',
    clueFalse: 'status-false',
    clueConvertBusiness: 'status-convert',
    businessWaitAllot: 'status-wait-allot',
    businessWaitFollow: 'status-wait-follow',
    businessFollowing: 'status-following',
    businessFalse: 'status-false',
    businessConvertCustomer: 'status-convert'
  }
  return statusClasses[type] || ''
}
</script>

<template>
  <div class="home">
    <!-- 欢迎标题和刷新区域 -->
    <div class="welcome-section">
      <div class="welcome-title">
        <h1>欢迎您, 进入客户关系管理系统</h1>
      </div>
      <div class="refresh-section">
        <el-button 
          type="primary" 
          icon="Refresh" 
          @click="refreshData"
          :loading="loading"
          size="small"
          circle
          style="width: 32px; height: 32px; display: flex; align-items: center; justify-content: center;"
        >
        </el-button>
        <span class="update-time" v-if="lastUpdateTime">
          更新时间: {{ lastUpdateTime }}
        </span>
      </div>
    </div>

    <!-- 错误提示 -->
    <el-alert
      v-if="error"
      title="数据加载提示"
      :description="error"
      type="warning"
      show-icon
      :closable="false"
      style="margin-bottom: 20px"
    />

    <!-- 概览卡片区域 -->
    <div class="overview-section">
      <!-- 线索概览 -->
      <div class="overview-card">
        <div class="card-header">
          <h2>线索概览</h2>
          <div class="total-indicator">
            总计: {{ overviewData.clueTotal }}
          </div>
        </div>
        <div class="card-content">
          <div class="data-grid">
            <div class="data-item" :class="getDataItemClass('clueWaitAllot')">
              <div class="data-label">待分配线索</div>
              <div class="data-value">{{ overviewData.clueWaitAllot }}</div>
              <div class="data-percentage" v-if="clueDataPercentage.clueWaitAllot > 0">
                {{ clueDataPercentage.clueWaitAllot }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('clueWaitFollow')">
              <div class="data-label">待跟进线索</div>
              <div class="data-value">{{ overviewData.clueWaitFollow }}</div>
              <div class="data-percentage" v-if="clueDataPercentage.clueWaitFollow > 0">
                {{ clueDataPercentage.clueWaitFollow }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('clueFollowing')">
              <div class="data-label">跟进中线索</div>
              <div class="data-value">{{ overviewData.clueFollowing }}</div>
              <div class="data-percentage" v-if="clueDataPercentage.clueFollowing > 0">
                {{ clueDataPercentage.clueFollowing }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('clueFalse')">
              <div class="data-label">跟进中</div>
              <div class="data-value">{{ overviewData.clueFalse }}</div>
              <div class="data-percentage" v-if="clueDataPercentage.clueFalse > 0">
                {{ clueDataPercentage.clueFalse }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('clueConvertBusiness')">
              <div class="data-label">转商机线索</div>
              <div class="data-value">{{ overviewData.clueConvertBusiness }}</div>
              <div class="data-percentage" v-if="clueDataPercentage.clueConvertBusiness > 0">
                {{ clueDataPercentage.clueConvertBusiness }}%
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 商机概览 -->
      <div class="overview-card">
        <div class="card-header">
          <h2>商机概览</h2>
          <div class="total-indicator">
            总计: {{ overviewData.businessTotal }}
          </div>
        </div>
        <div class="card-content">
          <div class="data-grid">
            <div class="data-item" :class="getDataItemClass('businessWaitAllot')">
              <div class="data-label">待分配商机</div>
              <div class="data-value">{{ overviewData.businessWaitAllot }}</div>
              <div class="data-percentage" v-if="businessDataPercentage.businessWaitAllot > 0">
                {{ businessDataPercentage.businessWaitAllot }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('businessWaitFollow')">
              <div class="data-label">待跟进商机</div>
              <div class="data-value">{{ overviewData.businessWaitFollow }}</div>
              <div class="data-percentage" v-if="businessDataPercentage.businessWaitFollow > 0">
                {{ businessDataPercentage.businessWaitFollow }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('businessFollowing')">
              <div class="data-label">跟进中商机</div>
              <div class="data-value">{{ overviewData.businessFollowing }}</div>
              <div class="data-percentage" v-if="businessDataPercentage.businessFollowing > 0">
                {{ businessDataPercentage.businessFollowing }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('businessFalse')">
              <div class="data-label">回收商机</div>
              <div class="data-value">{{ overviewData.businessFalse }}</div>
              <div class="data-percentage" v-if="businessDataPercentage.businessFalse > 0">
                {{ businessDataPercentage.businessFalse }}%
              </div>
            </div>
            <div class="data-item" :class="getDataItemClass('businessConvertCustomer')">
              <div class="data-label">转客户商机</div>
              <div class="data-value">{{ overviewData.businessConvertCustomer }}</div>
              <div class="data-percentage" v-if="businessDataPercentage.businessConvertCustomer > 0">
                {{ businessDataPercentage.businessConvertCustomer }}%
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作区域 -->
    <div class="quick-actions">
      <div class="action-item" @click="goToPage('/resource/course')">
        <div class="action-icon">
          <el-icon><Reading /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">课程管理</div>
          <div class="action-subtitle">课程信息维护</div>
        </div>
      </div>

      <div class="action-item" @click="goToPage('/resource/activity')">
        <div class="action-icon">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">活动管理</div>
          <div class="action-subtitle">营销活动管理</div>
        </div>
      </div>

      <div class="action-item" @click="goToPage('/clue/list')">
        <div class="action-icon">
          <el-icon><Promotion /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">线索管理</div>
          <div class="action-subtitle">潜在客户追踪</div>
        </div>
      </div>

      <div class="action-item" @click="goToPage('/business/list')">
        <div class="action-icon">
          <el-icon><Opportunity /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">商机管理</div>
          <div class="action-subtitle">销售机会管理</div>
        </div>
      </div>

      <div class="action-item" @click="goToPage('/customer')">
        <div class="action-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">客户管理</div>
          <div class="action-subtitle">客户信息维护</div>
        </div>
      </div>

      <div class="action-item" @click="goToPage('/system/log')">
        <div class="action-icon">
          <el-icon><Document /></el-icon>
        </div>
        <div class="action-content">
          <div class="action-title">日志统计</div>
          <div class="action-subtitle">系统操作日志</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

/* 欢迎区域 */
.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.welcome-title h1 {
  font-size: 32px;
  color: #333;
  margin: 0;
  font-weight: 500;
  font-family: 楷体, KaiTi, serif;
}

/* 刷新区域 */
.refresh-section {
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #f0f9ff;
  padding: 8px 15px;
  border-radius: 8px;
  border: 1px solid #e6f7ff;
}

.update-time {
  font-size: 14px;
  color: #1890ff;
  white-space: nowrap;
  font-weight: 500;
}

/* 概览区域 */
.overview-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.overview-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-header {
  background: linear-gradient(90deg, #1890ff 0%, #36cfc9 100%);
  color: #fff;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

/* 总计指示器 */
.total-indicator {
  font-size: 14px;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 12px;
  font-weight: 500;
}

.card-content {
  padding: 20px;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

/* 数据项样式 */
.data-item {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 20px 15px;
  text-align: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.data-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background-color: #1890ff;
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.data-item:hover {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
  transform: translateY(-1px);
}

.data-item:hover::before {
  transform: scaleX(1);
}

.data-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 10px;
  font-weight: 500;
}

.data-value {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

/* 百分比显示 */
.data-percentage {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
  background-color: rgba(24, 144, 255, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

/* 不同状态的颜色样式 */
.status-wait-allot {
  border-left: 4px solid #ff9800;
}

.status-wait-allot .data-value {
  color: #ff9800;
}

.status-wait-allot::before {
  background-color: #ff9800;
}

.status-wait-follow {
  border-left: 4px solid #e74c3c;
}

.status-wait-follow .data-value {
  color: #e74c3c;
}

.status-wait-follow::before {
  background-color: #e74c3c;
}

.status-following {
  border-left: 4px solid #27ae60;
}

.status-following .data-value {
  color: #27ae60;
}

.status-following::before {
  background-color: #27ae60;
}

.status-false {
  border-left: 4px solid #95a5a6;
}

.status-false .data-value {
  color: #95a5a6;
}

.status-false::before {
  background-color: #95a5a6;
}

.status-convert {
  border-left: 4px solid #8e44ad;
}

.status-convert .data-value {
  color: #8e44ad;
}

.status-convert::before {
  background-color: #8e44ad;
}

/* 快捷操作样式 */
.quick-actions {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.action-item {
  background-color: #fff;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 25px 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-item:hover {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}

.action-icon {
  margin-bottom: 15px;
}

.action-icon .el-icon {
  font-size: 36px;
  color: #1890ff;
}

.action-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.action-subtitle {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .overview-section {
    flex-direction: column;
  }
  
  .quick-actions {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .home {
    padding: 15px;
  }
  
  .welcome-section {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .welcome-title h1 {
    font-size: 24px;
  }
  
  .data-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .data-item {
    padding: 15px 10px;
  }
  
  .data-value {
    font-size: 20px;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .total-indicator {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .data-grid {
    grid-template-columns: 1fr;
  }
  
  .welcome-title h1 {
    font-size: 20px;
  }
}

/* 加载状态动画 */
.el-button.is-loading .el-icon-loading {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误提示样式调整 */
:deep(.el-alert__description) {
  color: #606266;
  font-size: 14px;
}
</style>
